var section = {
	orkutAuthUrl: null,
	profileImage: null,
	
	
	init : function( ){
		$.getScriptSafe('/static/settings.js', section.loadMlPack);
	},
	
	loadMlPack : function(){
		$.getScriptSafe('/static/js/lib/ml-utils.js', section.allLoadsComplete);
	},
	
	allLoadsComplete: function () {
		trace('allLoadsComplete');
		
		section.profileImage = $('input[name="profile_image"]').val();
		section.verifyFaceConnect();
		section.verifyOrkutConnect();
		
		$('.social-networks .enable-your-store .nav-connect.face').bind('click', function (e) {
			e.preventDefault();
			$('.fb_button_medium').click();
		});
	
		$('.social-networks .enable-your-store .nav-connect.orkut').bind('click', function (e) {
			e.preventDefault();
			section.getOrkutConnect();
		});
	
		$('.social-networks a.bt-continue').bind('click', function (e) {
			e.preventDefault();
			$('#main-form').submit();
		});
	},
	
	verifyFaceConnect: function(){
      trace('verifyFaceConnect');   

		if(window.FB == undefined){ 
	      trace('FB undefined');   
			setTimeout(section.verifyFaceConnect, 2000);	
			return;
		}
		
		var fbSession = FB.getSession();
      
		if(fbSession == null){ 
	      trace('FB Session undefined');
			return;   
		}
		
		var img  = section.profileImage == '' ? 'http://graph.facebook.com/{0}/picture'.format(fbSession.uid) : section.profileImage;
		$('li.face strong').text($('input[name="profile_name"]').val()._slice(17).replace(/\.../g, ''));
		$('li.face .connected').show();
		$('li.face img').css('background-image', 'url("{0}")'.format(img));
		$('li.face span:eq(0)').text('Conectado');
		$('input[name="facebook_id"]').val(fbSession.uid);
		$('input[name="facebook_access_token"]').val(fbSession.access_token);
	},
	
	faceLogout: function(){
		$('li.face strong').text('Facebook');
		$('li.face .connected').hide();
		$('li.face img').css('background-image', 'url("/static/img/sections/cadastro/redes-sociais/ico-facebook.png")');
		$('li.face span:eq(0)').text('Não Conectado');
	},
	
	verifyOrkutConnect: function(){
		var orkutID = $('input[name="orkut_id"]').val();
		var profileKey = $('input[name="profile_key"]').val();
		
		if(orkutID == ''){
			if(profileKey == '') return;

			$.ajax({
				url: settings.auth.orkut,
				data: {profile_key: profileKey},
				success: function() {
					section.orkutAuthUrl = arguments[0].url;
				},
				dataType: 'json'
			});
		}else{
			$('li.orkut strong').text($('input[name="profile_name"]').val()._slice(17).replace(/\.../g, ''));
			$('li.orkut .connected').show();
			if(section.profileImage != '') $('li.orkut img').css('background-image', 'url("{0}")'.format(section.profileImage));
			$('li.orkut span:eq(0)').text('Conectado');
		};
	},
	
	getOrkutConnect: function(e){
		if(section.orkutAuthUrl != null) document.location.href = section.orkutAuthUrl;
	}
};

$(document).ready(section.init)